#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <wait.h>

int main()
{
    pid_t id = fork();

    if (id == 0)
    {
        printf("子进程: pid: %d ppid: %d\n", getpid(), getppid());
        sleep(5);
        printf("子进程exit\n");
        exit(0);
    }
    else if (id > 0)
    {
        printf("父进程: pid: %d ppid: %d\n", getpid(), getppid());
        while (1)
        {
            int stat = 0;
            pid_t ret = waitpid(id, &stat, WNOHANG);
            if (ret > 0)
            {
                printf("exit code = %d\n", WEXITSTATUS(stat));
                if (!WIFEXITED(stat))
                    printf("异常退出 exit sig = %d\n", stat & 0x7F);
                break;
            }
            else if (ret == 0)
            {
                printf("waiting..\n");
                sleep(1);
            }
            else
            {
                printf("wait error\n");
                break;
            }
        }
    }
    else
        printf("fork error\n");

    return 0;
}
